package com.example.controller;


import cn.hutool.core.date.DateUtil;
import com.example.common.MinioProperties;
import com.example.common.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Parameter;

import java.util.Date;
import java.util.UUID;

/**
 * 通用接口
 */
@ApiSupport(author = "wjp", order = 2)
@Tag(name = "通用接口", description = "文件上传相关接口")
@RestController
@RequestMapping("/files")
@Slf4j
public class CommonController {

    @Autowired
    private MinioProperties minioProperties;


    @PostMapping("/upload")
    @Operation(summary = "文件上传到MinIO", description = "上传单个文件到MinIO存储，返回文件URL")
    public Result fileUpload(@Parameter(description = "待上传的文件") MultipartFile file) {
        log.info("文件上传开始", file);
        try {
            // 创建minio对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();

            // 判断桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {       // 如果不存在，那么此时就创建一个新的桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {  // 如果存在打印信息
                System.out.println("该文件夹已存在");
            }

            // 获取文件名
            //每个文件都有唯一的名称
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileName = dateDir + "/" + uuid + file.getOriginalFilename();

            // 上传文件到minio
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build());
            // 返回文件路径
            String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;


            return Result.success(url);

        } catch (Exception e) {
            log.error("文件上传失败：{}", e);
        }
        return Result.error("上传失败");
    }
}
